forum

home / developersection / forums / synchronized thread method in java

Synchronized thread method in java

Elena Glibart 2755 29-Oct-2014
I have one question about thread. I have following Thread class and creating 2 thread objects.

public class MyThread extends Thread{
 
    String name="";
 
    public MyThread(String string) {
        name=string;
    }   
 
    @Override
    public void run() {
        callMe();
    }        
    synchronized private void callMe() {
        System.out.println("Started");
        for (int i = 1; i <= 5; i++) {
            System.out.println(name+" = "+i);
        }          
    }
 
 
    public static void main(String[] args) {                    MyThread a = new MyThread("A");
        MyThread b = new MyThread("B");
 
        a.start();
        b.start();
    }       }

Output:

Started

Started

B = 1

B = 2

A = 1

A = 2

B = 3

A = 3

B = 4

A = 4

B = 5

A = 5

my question is: why loop is NOT executed one after other? I have used synchronized keyword.


Updated on 29-Oct-2014
Can you answer this question?

Answer

1 Answers

Liked By